import wepy from 'wepy'
import Modal from './modal'
export class CommonUtil {
  static copy (obj) {
    return JSON.parse(JSON.stringify(obj))
  }
  /**
   *get getByteLen
   * @param {Sting} val input value
   * @returns {number} output value
   */
  static getByteLength (val) {
    let len = 0
    if (this.isNotBlank(val)) {
      for (let i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/gi) != null) {
          len += 1
        } else {
          len += 0.5
        }
      }
    }
    return Math.floor(len)
  }
  /**
   * 函数节流
   * @param fn
   * @param gapTime
   * @returns {Function}
   */
  static throttle (fn, gapTime) {
    if (gapTime == null || gapTime === undefined) {
      gapTime = 1500
    }
    let _lastTime, _nowTime
    return function () {
      _nowTime = new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
        fn()
        _lastTime = _nowTime
      }
    }
  }
  // 去抖
  static debounce (func, wait, immediate) {
    let timeout, args, context, timestamp, result
    const later = function() {
      // 据上一次触发时间间隔
      const last = +new Date() - timestamp
      // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
      if (last < wait && last > 0) {
        timeout = setTimeout(later, wait - last)
      } else {
        timeout = null
        // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
        if (!immediate) {
          result = func.apply(context, args)
          if (!timeout) context = args = null
        }
      }
    }
    return function(...args) {
      context = this
      timestamp = +new Date()
      const callNow = immediate && !timeout
      // 如果延时不存在，重新设定延时
      if (!timeout) timeout = setTimeout(later, wait)
      if (callNow) {
        result = func.apply(context, args)
        context = args = null
      }
      return result
    }
  }
  /**
   * This is just a simple version of deep copy
   * Has a lot of edge cases bug
   * If you want to use a perfect deep copy, use lodash's _.cloneDeep
   */
  static deepClone (source) {
    if (!source && typeof source !== 'object') {
      throw new Error('error arguments', 'shallowClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = this.deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    })
    return targetObj
  }
  // 清除数据重复元素
  static uniqueArray (arr) {
    return Array.from(new Set(arr))
  }
  // 判断是否为外链
  static isExternal (path) {
    return /^(https?:|mailto:|tel:)/.test(path)
  }
  // 生成包含数字 字母 下划线的随机数
  static createRandom (len) {
    let str = ''
    let arr = ['_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    for (let i = 0; i < len; i++) {
      let pos = Math.round(Math.random() * (arr.length - 1))
      str += arr[pos]
    }
    return str
  }
  static isBlank (value) {
    if (value !== null && value !== undefined && value.toString().replace(/^\s+|\s+$/g, '') !== '') {
      return false
    }
    return true
  }
  static isNotBlank (value) {
    return !this.isBlank(value)
  }
  static isBlankObj(value) {
    if (value == null || value === undefined) {
      return true
    }
    return false
  }
  static isNotBlankObj(value) {
    return !this.isBlankObj(value)
  }
  static tel(value) {
    console.log('notBlank',this.isNotBlank(value))
    console.log('test',/^1[34578]\d{9}$/.test(value))
    return this.isNotBlank(value) && /^1[34578]\d{9}$/.test(value)
  }
  static isNotBlankArray(...vals) {
    let result = this.isNotBlank(vals)
    if (result && vals.length > 0) {
      result = vals.every(val => {
        return this.isNotBlank(val)
      })
    } else result = false
    return result
  }
  // 清理数组空白项(空值项)
  static cleanArray(actual) {
    let newArray = []
    if (this.isNotBlankArray(actual)) {
      newArray = actual.filter(m => this.isNotBlank(m))
    }
    return newArray
  }
  static isUnDeleted(val) {
    if (val === 'UN_DELETED' || val === 0 || val === '0') return true
    return false
  }
}

export class NumberUtil {
  /**
   * 价格显示格式化 1,231.00元
   * @param money 价格值
   * @param precision 精度
   * @param isUnit 是否需要单位(人民币：元、万元),默认不写
   * @param unit 单位, 不填则在前面加'￥'
   * @returns {string}
   */
  static format (money, precision, isUnit) {
    // console.log('====numberutil.format===>', money)
    if (CommonUtil.isBlank(money)) money = 0
    precision = precision || 0
    if (precision > 2) precision = 2
    isUnit = isUnit === undefined ? false : isUnit
    let unit = ''
    if (isUnit) unit = '￥'
    money = parseFloat(money) || 0
    if (money > 0) {
      money = money.toFixed(precision) + ''
      // _integer -- 整数部分，_dec -- 小数部分, _comma--每三位数用逗号分隔
      let _integer = money.split('.')[0].split('').reverse()
      let _dec = ''
      let _comma = ''
      if (precision > 0) {
        _dec = '.' + money.split('.')[1]
      }
      for (let i = 0; i < _integer.length; i++) {
        _comma += _integer[i] + ((i + 1) % 3 === 0 && (i + 1) !== _integer.length ? ',' : '')
      }
      return unit + _comma.split('').reverse().join('') + _dec
    }
    money = '0.'
    for (let i = 0; i < precision; i++) {
      money += '0'
    }
    return unit + money
  }

  static parse (money, precision) {
    if (CommonUtil.isBlank(money)) money = 0
    precision = precision || 0
    if (precision > 2) precision = 2
    let unit = ''
    money = parseFloat(money) || 0
    if (money > 0) {
      money = money.toFixed(precision)
    } else {
      money = '0.'
      for (let i = 0; i < precision; i++) {
        money += '0'
      }
    }
    return unit + money
  }

  static add (arg1, arg2) {
    let r1, r2, m
    try { r1 = arg1.toString().split('.')[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split('.')[1].length } catch (e) { r2 = 0 }
    let d = Math.max(r1, r2)
    m = Math.pow(10, d)
    return ((arg1 * m + arg2 * m) / m).toFixed(d)
  }
  static subtract (arg1, arg2) {
    let r1, r2, m, n
    try { r1 = arg1.toString().split('.')[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split('.')[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    // 动态控制精度长度
    n = Math.max(r1, r2)
    // n=(r1=r2)?r1:r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n)
  }
  static multiply (arg1, arg2) {
    let m = 0
    let s1 = arg1.toString()
    let s2 = arg2.toString()
    try { m += s1.split('.')[1].length } catch (e) { }
    try { m += s2.split('.')[1].length } catch (e) { }
    return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
  }
  static divide (arg1, arg2) {
    let t1 = 0
    let t2 = 0
    let r1, r2
    try { t1 = arg1.toString().split('.')[1].length } catch (e) {}
    try { t2 = arg2.toString().split('.')[1].length } catch (e) {}
    r1 = Number(arg1.toString().replace('.', ''))
    r2 = Number(arg2.toString().replace('.', ''))
    return (r1 / r2) * Math.pow(10, t2 - t1)
  }
}
export class DateUtil{
  static parseTime(date, fmt) {
    if (date == undefined || date == '' || date == null) {
      return ''
    }
    if(typeof date=='string'){
      date = date.replace('.','-').replace('.','-').replace('.','-');
    }

    date = date == undefined ? new Date() : new Date(date);
    //date = typeof date == 'number' ? new Date(date) : date;
    fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
    var obj =
      {
        'y': date.getFullYear(), // 年份，注意必须用getFullYear
        'M': date.getMonth() + 1, // 月份，注意是从0-11
        'd': date.getDate(), // 日期
        'q': Math.floor((date.getMonth() + 3) / 3), // 季度
        'w': date.getDay(), // 星期，注意是0-6
        'H': date.getHours(), // 24小时制
        'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
        'm': date.getMinutes(), // 分钟
        's': date.getSeconds(), // 秒
        'S': date.getMilliseconds() // 毫秒
      };
    var week = ['天', '一', '二', '三', '四', '五', '六'];
    for (var i in obj) {
      fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
        var val = obj[i] + '';
        if (i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
        for (var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
        return m.length == 1 ? val : val.substring(val.length - m.length);
      });
    }
    return fmt;
  }
}


export class WxUtil {
  static wxPay(param) {
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        ...param,
        complete: res => {
          resolve(res)
        }
      })
    })
  }

  static wxGetLocation() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          resolve(res)
          // param.latitude = res.latitude
          // param.longitude = res.longitude
          // param.speed = res.speed
          // param.accuracy = res.accuracy
        },
        fail: function(res) {
          resolve(res)
        }
      })
    })
  }

  /**
   * 兼容性判断
   */
  static canIUse(str) {
    if (wx.canIUse) {
      return wx.canIUse(str)
    } else {
      return false
    }
  }
  /**
   * 检查SDK版本
   */
  static isSDKExipred() {
    const {SDKVersion} = wx.getSystemInfoSync()
    console.info(`[version]sdk ${SDKVersion}`)
    return SDKVersion == null || SDKVersion < '1.2.0'
  }
  /**
   * 检查SDK版本
   */
  static checkSDK() {
    if (this.isSDKExipred()) {
      Modal.modal('您的微信版本太低，为确保正常使用，请尽快升级')
    }
  }
}
